
import 'package:flutter/material.dart';
import 'package:flutter_fronter_service/tools/constant.dart';
import 'package:get/get.dart';

import '../api/orderApi.dart';
import '../controller/userController.dart';
import '../model/OrderDetail.dart';
import '../model/order_entity.dart';
import '../model/properties_entity.dart';
import '../model/sku_entity.dart';
class OrderListPage extends StatefulWidget {
  const OrderListPage({super.key});

  @override
  State<OrderListPage> createState() => _OrderListPageState();
}

class _OrderListPageState extends State<OrderListPage> with SingleTickerProviderStateMixin{

  late TabController _tabController;
  late int initIndex = 0;
  bool isLogin = false;
  bool isLoading = true;
  UserController userController = Get.find<UserController>();


  //获取全部订单
  late List<OrderEntity> orderList = [];
  Future<void> _loadAllOrders() async{
    //判断是否登录
    if(userController.user.value.id>0) {
      //登录
      isLogin = true;
      var res = await getAllOrderApi();
      //判断
      if (res["data"].runtimeType.toString() == "List<dynamic>" &&
          res["data"].length > 0) {
        //解析数据
        for (var order in res["data"]) {
          //解析order
          OrderEntity orderEntity = OrderEntity.fromJson(order);
          List<OrderDetail> orderDetails = [];
          //解析商品
          for (int i = 0; i < order["detailsVos"].length; i++) {
            //规格列表
            late RxList<PropertiesEntity> itemSpecList = <PropertiesEntity>[]
                .obs;
            late String goodsSpec = "";
            //属性解析
            order["detailsVos"][i]["skuItemVo"]["itemSpec"].forEach((item) =>
                itemSpecList.add(PropertiesEntity.fromJson(item)));
            SkuEntity sku = SkuEntity.fromJson(
                order["detailsVos"][i]["skuItemVo"]);
            sku.goodsPrice = order["detailsVos"][i]["skuItemVo"]["goodsPrice"];
            sku.goodsName = order["detailsVos"][i]["skuItemVo"]["goodsName"];
            sku.itemSpec = itemSpecList;
            itemSpecList.forEach((element) {
              goodsSpec = goodsSpec + ' ' + element.value;
            });
            //订单细则
            OrderDetail orderDetail = OrderDetail(
              order["detailsVos"][i]["quantity"],
              sku,
              goodsSpec,
            );
            orderDetails.add(orderDetail);
          }
          //商品赋值
          orderEntity.orderDetails = orderDetails;
          //添加至列表
          orderList.add(orderEntity);
        }
      }
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    //接收跳转参数
    initIndex = Get.arguments["initIndex"]>2?0:Get.arguments["initIndex"];
    //初始化tabbar
    _tabController = TabController(length: 3, vsync: this,initialIndex: initIndex);
    _loadAllOrders();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('订单列表'),
        bottom: TabBar(
          controller: _tabController,
          labelColor: Colors.red,
          unselectedLabelColor: Colors.black,
          indicatorColor: Colors.red,
          indicatorWeight: 2.0,
          tabs: const [
            Tab(text: '全部'),
            Tab(text: '待付款'),
            Tab(text: '待发货'),
          ],
        ),
      ),
      body: isLogin?(isLoading ? const Center(child: CircularProgressIndicator()) : TabBarView(
        controller: _tabController,
        children: [
          buildOrderListView(orderList),
          buildOrderListView(orderList.where((order) => order.orderState == ORDER_STATE_UNPAID).toList()),
          buildOrderListView(orderList.where((order) => order.orderState == ORDER_STATE_PAID).toList()),
        ],
      )):const Center(
          child: Text("未登录")
    ));
  }

  //构建订单列表
  Widget buildOrderListView(List<OrderEntity> orderList) {
    return ListView.builder(
      itemCount: orderList.length,
      itemBuilder: (context, index) {
        return GestureDetector(
          onTap: (){
            Get.toNamed('/orderDetail', arguments: {"id":orderList[index].id});
          },
          child: Card(
            margin: EdgeInsets.all(8),
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 订单状态
                  Align(
                    alignment: Alignment.topRight,
                    child: Text(
                      orderList[index].orderState != ORDER_STATE_PAID?"未支付":"待发货",
                      style: TextStyle(color: orderList[index].orderState != ORDER_STATE_PAID?Colors.red:Colors.blue, fontWeight: FontWeight.bold),
                    ),
                  ),
                  SizedBox(height: 8),
                  // 构建子项
                  for(var orderDetail in orderList[index].orderDetails)
                    buildOrderItem(orderDetail),
                  SizedBox(height: 8),
                  // 实付金额
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Text('实付金额: ¥'),
                      Text('${orderList[index].orderAmount}', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold,color: Colors.red)),
                    ],
                  ),
                  SizedBox(height: 8),
                  // 按钮
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      if (orderList[index].orderState == ORDER_STATE_UNPAID)
                        ElevatedButton(
                          onPressed: () {
                            Get.toNamed('/orderDetail', arguments: {"id":orderList[index].id});
                          },
                          child: Text('立即支付'),
                        )
                      else if (orderList[index].orderState == ORDER_STATE_PAID)
                        ElevatedButton(
                          onPressed: () {
                            // 再次购买逻辑
                          },
                          child: Text('再次购买'),
                        ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );

      },
    );
  }

  //构建订单列表项
  Widget buildOrderItem(OrderDetail orderDetail){
    return Row(
      children: [
        Image.network(
          orderDetail.skuEntity.itemImg,
          width: 50,
          height: 50,
          fit: BoxFit.cover,
        ),
        SizedBox(width: 8),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(orderDetail.skuEntity.goodsName, style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
              Text(orderDetail.spec),
              Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text('¥${orderDetail.skuEntity.goodsPrice}', style: TextStyle(color: Colors.red)),
                    Text('X ${orderDetail.quantity}',style: TextStyle(color: Colors.black45),),
                  ]
              )
            ],
          ),
        ),
      ],
    );
  }
}

